//select2格式化返回
function select2FormatRepo (result,select) {
    if (result.loading) return result.text;
    var openUrl = select.attr("openUrl")
    var markup = '<div class="clearfix">' +
        '<div class="col-sm-2"><a href="'+openUrl+result.id+'">' + result.id + '</a></div>' +
        '<div class="col-sm-10">' + result.text + '</div>' +
        '</div>';
    return markup;
}
//select2格式化选中后
function select2formatRepoSelection (selection,select) {
    selection.selected = true;
    var openUrl = select.attr("openUrl")
    return '<a href="' + openUrl + selection.id + '">' + selection.text + '</a>';
}
//$(".multiple-select2-ajax")
function initMultipleSelect2Ajax($parentDivDom) {
    if($parentDivDom.length<1){
        return
    }
    //多选初始化
    $parentDivDom.find(".multiple-select2-ajax").each(function () {
        var _t = $(this)
        $(this).select2({
            ajax: {
                url: "admin/"+$(this).attr("foreignTableName")+"/type_ahead_search",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        keyword: params.term, // search term
                        foreignJavaField:$(this).attr("foreignJavaField"),
                        selectValue:$(this).attr("selectValue"),
                        page: params.page
                    };
                },
                processResults: function (data, params) {
                    params.page = params.page || 1;
                    return {
                        results: data,
                        pagination: {
                            more: (params.page * 30) < 10
                        }
                    };
                },
                cache: true
            },
            escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
            minimumInputLength: 0,
            width:"100%",
            templateResult: function(result){return select2FormatRepo(result,_t)}, // omitted for brevity, see the source of this page
            templateSelection: function(result){return  select2formatRepoSelection(result,_t)} // omitted for brevity, see the source of this page
        })
    })
}
//$(".single-select2-ajax")
function initSingleSelect2Ajax($parentDivDom) {
    if($parentDivDom.length<1){
        return
    }
//单选初始化
    $parentDivDom.find(".single-select2-ajax").each(function () {
        var _t = $(this)
        $(this).select2({
            ajax: {
                url: "admin/"+$(this).attr("foreignTableName")+"/type_ahead_search",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        keyword: params.term, // search term
                        foreignJavaField:$(this).attr("foreignJavaField"),
                        selectValue:$(this).attr("selectValue"),
                        page: params.page
                    };
                },
                processResults: function (data, params) {
                    params.page = params.page || 1;
                    return {
                        results: data,
                        pagination: {
                            more: (params.page * 30) < 10
                        }
                    };
                },
                cache: true
            },
            escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
            minimumInputLength: 0,
            width:"100%",
            templateResult: function(result){return select2FormatRepo(result,_t)}, // omitted for brevity, see the source of this page
            templateSelection: function(result){return  select2formatRepoSelection(result,_t)} // omitted for brevity, see the source of this page
        })
    })
}

//$("#park_code").empty().append('<option id="'+code+'" value="'+code+'">'+name+'</option>').trigger('change');
//自动设置默认值 $(".single-select2-ajax")
function autoSetSingleSelect2Value($parentDivDom) {
    if($parentDivDom.length<1){
        return
    }
    var foreignTableNameMap = {}
    var foreignJavaFieldMap = {}
    $parentDivDom.find(".single-select2-ajax").each(function (index,item) {
        var hiddenValue = $(this).attr("values")
        var name = $(this).attr("name")
        var foreignTableName = $(this).attr("foreignTableName")
        var foreignJavaField = $(this).attr("foreignJavaField")
        var selectValue = $(this).attr("selectValue")
        if(hiddenValue!=''){
            var tableList = foreignTableNameMap[foreignTableName]
            if(!tableList){
                tableList = []
                foreignTableNameMap[foreignTableName] = tableList
            }
            var item = {}
            item[foreignJavaField] = hiddenValue
            tableList.push(item)
            foreignJavaFieldMap[foreignTableName] = foreignJavaField
        }
    })

    //查询值
    for(var foreignTableName in foreignTableNameMap){
        var tableList = clearRepeat(foreignTableNameMap[foreignTableName])
        var foreignJavaField = foreignJavaFieldMap[foreignTableName]
        //去重
        if(tableList!=null && tableList.length>0){
            var reqUrl = "admin/"+foreignTableName+"/batch_search_type_ahead"
            $.getJSON(reqUrl,{date:new Date().getTime(),searchMapListJson:JSON.stringify(tableList),foreignJavaField:foreignJavaField},function(data){
                if(data.code == 0){
                    setSingleValue($parentDivDom,data.info)
                }
            })
        }
    }
}

function clearRepeat(tableList){
    if(tableList!=null && tableList.length>0){
        var existMap = {}
        for(var i=0;i<tableList.length;i++){
            var item = tableList[i]
            for(var k in item){
                var itemValue = item[k]
                var value = existMap[itemValue]
                if(value){
                    tableList.splice(i,1)
                    i--
                }else {
                    existMap[itemValue]=1
                }
            }

        }
    }
    return tableList;
}
function setSingleValue($parentDivDom,resultMap){
    var useForeignTableName = resultMap.foreignTableName
    var returnMap = resultMap.returnMap;
    $parentDivDom.find(".single-select2-ajax").each(function (index,item) {
        var name = $(this).attr("name")
        var hiddenValue = $(this).attr("values")
        var foreignTableName = $(this).attr("foreignTableName")
        var foreignJavaField = $(this).attr("foreignJavaField")
        var selectValue = $(this).attr("selectValue")
        if(selectValue==''){
            selectValue = resultMap.selectValue;
        }
        if(foreignTableName == useForeignTableName){
            if(hiddenValue!='' && selectValue!=''){
                var entity = returnMap[hiddenValue];
                if(entity){
                    var showValue = []
                    var fieldsIdArr = selectValue.split(",");
                    for(var i=0;i<fieldsIdArr.length;i++){
                        var field = fieldsIdArr[i];
                        showValue.push(entity[field])
                    }
                    $(this).empty().append('<option  value="'+hiddenValue+'">'+showValue.join('-')+'</option>').trigger('change');
                }
            }
        }
    })
}










//$("#park_code").empty().append('<option id="'+code+'" value="'+code+'">'+name+'</option>').trigger('change');
//自动设置默认值 $(".single-select2-ajax")
function autoSetMultipleSelect2Value($parentDivDom) {
    if($parentDivDom.length<1){
        return
    }
    var foreignTableNameMap = {}
    var foreignJavaFieldMap = {}
    $parentDivDom.find(".multiple-select2-ajax").each(function (index,item) {
        var hiddenValue = $(this).attr("values")
        var name = $(this).attr("name")
        var foreignTableName = $(this).attr("foreignTableName")
        var foreignJavaField = $(this).attr("foreignJavaField")
        var selectValue = $(this).attr("selectValue")
        if(hiddenValue!=''){
            var tableList = foreignTableNameMap[foreignTableName]
            if(!tableList){
                tableList = []
                foreignTableNameMap[foreignTableName] = tableList
            }
            foreignJavaFieldMap[foreignTableName] = foreignJavaField

            var values = hiddenValue.split(",")
            for(var i=0;i<values.length;i++){
                var id = values[i]
                if(id!=''){
                    var item = {}
                    item[foreignJavaField] = id
                    tableList.push(item)
                }
            }
        }
    })

    //查询值
    for(var foreignTableName in foreignTableNameMap){
        var tableList = clearRepeat(foreignTableNameMap[foreignTableName])
        var foreignJavaField = foreignJavaFieldMap[foreignTableName]
        //去重
        if(tableList!=null && tableList.length>0){
            var reqUrl = "admin/"+foreignTableName+"/batch_search_type_ahead"
            $.getJSON(reqUrl,{date:new Date().getTime(),searchMapListJson:JSON.stringify(tableList),foreignJavaField:foreignJavaField},function(data){
                if(data.code == 0){
                    setMultipleValue($parentDivDom,data.info)
                }
            })
        }
    }
}


function setMultipleValue($parentDivDom,resultMap){
    var useForeignTableName = resultMap.foreignTableName
    var returnMap = resultMap.returnMap;
    $parentDivDom.find(".multiple-select2-ajax").each(function (index,item) {
        var name = $(this).attr("name")
        var hiddenValue = $(this).attr("values")
        var foreignTableName = $(this).attr("foreignTableName")
        var foreignJavaField = $(this).attr("foreignJavaField")
        var selectValue = $(this).attr("selectValue")
        if(selectValue==''){
            selectValue = resultMap.selectValue;
        }
        if(foreignTableName == useForeignTableName){
            if(hiddenValue!='' && selectValue!=''){
                $(this).empty();
                var values = hiddenValue.split(",")
                for(var i=0;i<values.length;i++){
                    var id = values[i]
                    if(id!=''){
                        var entity = returnMap[id];
                        if(entity){
                            var showValue = []
                            var fieldsIdArr = selectValue.split(",");
                            for(var j=0;j<fieldsIdArr.length;j++){
                                var field = fieldsIdArr[j];
                                showValue.push(entity[field])
                            }
                            $(this).append('<option selected  value="'+id+'">'+showValue.join('-')+'</option>');
                        }
                    }
                }
                $(this).trigger('change');
            }
        }
    })
}